package com.zhengbing.tj;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.zhengbing.tj.entity.User;
import com.zhengbing.tj.service.UserService;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import javax.sql.DataSource;
import java.sql.Connection;

@SpringBootApplication
@MapperScan("com.zhengbing.tj.mapper")
public class App implements CommandLineRunner {
    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        // 数据库连接检查
        checkDatabaseConnection();
    }

    private void checkDatabaseConnection() {
        try (Connection conn = dataSource.getConnection()) {
            System.out.println("✅ 数据库连接成功: " + conn.getMetaData().getURL());
        } catch (Exception e) {
            System.err.println("⚠️ 警告: 数据库连接失败: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    public CommandLineRunner insertZhengbingUser(UserService userService) {
        return args -> {
            String username = "zhengbing";
            String password = "Zb@654321";
            String email = "mydreambing@126.com";
            // 检查是否已存在
            if (userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getName, username)) == null) {
                User user = new User();
                user.setName(username);
                user.setPassword(SecureUtil.md5(password));
                user.setEmail(email);
                userService.save(user);
                System.out.println("已插入用户: zhengbing");
            } else {
                System.out.println("用户 zhengbing 已存在");
            }
        };
    }
}